(ns liberator-sample.core.tutorial.getting-started
  (:require [liberator.core :refer [resource defresource]]
            [ring.middleware.params :refer [wrap-params]]
            [compojure.core :refer [defroutes routes ANY]]
            [org.httpkit.server :as server])
  (:use clojure.pprint))

(declare app foo bar counter example parameter txt)

(defresource example :handle-ok "This is the example")
(defresource parameter [txt]
             :available-media-types ["text/plain"]
             :handle-ok (fn [_] (format "The text is %s" txt)))


(defroutes app
           (ANY "/" [] (resource)))

(defroutes foo
           (ANY "/foo" []
                (resource :available-media-types ["text/html"]
                          :handle-ok "<html>Hello, Internet.</html>")))

(defroutes bar
           (ANY "/bar" []
                (resource :available-media-types ["text/html"]
                          :handle-ok (fn [ctx]
                                       (format "<html>It's %d milliseconds since the beginning of the epoch." (System/currentTimeMillis)))))
           (ANY "/bar/:txt" [txt] (parameter txt)))

(def _counter (ref 0))
(defroutes counter
           (ANY "/counter" []
                (resource :handle-ok (fn [_] (format "The counter is %d" @_counter)))))

(def handler
  (-> (routes app foo bar counter)
      wrap-params))

(server/run-server handler {})